package com.li.jiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.li.jiang.Exception.DataException;
import com.li.jiang.obj.pojo.CompanyPhotos;
import com.li.jiang.mapper.CompanyPhotosMapper;
import com.li.jiang.obj.pojo.Photos;
import com.li.jiang.service.ICompanyPhotosService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 公司图片表 服务实现类
 * </p>
 *
 * @author 李江
 * @since 2024-05-16
 */
@Service
public class CompanyPhotosServiceImpl extends ServiceImpl<CompanyPhotosMapper, CompanyPhotos> implements ICompanyPhotosService {
    @Autowired
    private PhotosServiceImpl photosService;
    @Override
    public List<Photos> getCompanyPhotos(Long cid) {
        //1.得到公司图片关系实体
        List<CompanyPhotos> l = lambdaQuery().eq(CompanyPhotos::getCid,cid).list();
        //2.得到图片id集合
        List<Long> pids = l.stream().map(CompanyPhotos::getPid).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(pids)){
            return Collections.emptyList();
        }
        System.out.println("查询图片id:"+pids);
        //3.根据id集合查询图片
        return photosService.lambdaQuery().in(Photos::getId,pids).list();
    }

    @Transactional
    @Override
    public boolean removeByName(String name) {
        //1.获取图片
        Photos p = photosService.getPhotoByName(name);
        //2.删除数据库数据图片
        photosService.removeById(p.getId());
        new File(p.getAddress()).delete();
        //3.删除公司图片关系
        LambdaQueryWrapper<CompanyPhotos> wrapper
                = new LambdaQueryWrapper<CompanyPhotos>()
                .eq(CompanyPhotos::getPid,p.getId());
        return this.remove(wrapper);

    }

    @Transactional
    @Override
    public boolean addCompanyPhotos(Long cid, String name) {
        Photos p = photosService.getPhotoByName(name);
        if(p==null){
            throw new DataException("照片不存在");
        }
        CompanyPhotos companyPhotos = new CompanyPhotos();
        companyPhotos.setCid(cid);
        companyPhotos.setPid(p.getId());
        System.out.println("保存图片关系:"+companyPhotos);
        return this.save(companyPhotos);
    }
}
